/**
 * 系统管理 用户管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row
      :gutter="20"
      style="height: 100%; min-height: 400px; margin-top: 20px"
    >
      <!--侧边部门数据-->
      <el-col
        :xs="9"
        :sm="6"
        :md="5"
        :lg="4"
        :xl="4"
        style="height: calc(100vh - 150px)"
      >
        <div class="head-container">
          <el-input
            v-model="queryData.deptName"
            clearable
            size="small"
            placeholder="输入部门名称搜索"
            prefix-icon="el-icon-search"
            class="filter-item"
            @input="getDeptDatas"
          />
        </div>
        <div
          style="height: calc(100% - 50px); overflow: scroll; margin-top: 20px"
        >
          <el-tree
            :data="deptDatas"
            :props="defaultProps"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>

      <!--用户数据-->
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <!--工具栏-->
        <div class="head-container">
          <div>
            <!-- 搜索 -->
            <el-input
              v-model="queryData.blurry"
              clearable
              size="small"
              placeholder="输入名称"
              style="width: 200px"
              class="filter-item"
              @keyup.enter.native="toQuery"
            />
            <el-date-picker
              v-model="queryData.time"
              type="datetimerange"
              size="small"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
            >
            </el-date-picker>
            <el-select
              v-model="queryData.enabled"
              clearable
              size="small"
              placeholder="状态"
              class="filter-item"
              style="width: 90px"
            >
              <el-option
                v-for="item in enabledTypeOptions"
                :key="item.key"
                :label="item.name"
                :value="item.key"
              />
            </el-select>
          </div>
          <el-row style="margin-top: 20px">
            <el-button
              size="small"
              icon="el-icon-plus"
              type="primary"
              @click="add()"
              >新增</el-button
            >
            <el-button
              size="small"
              icon="el-icon-delete"
              type="primary"
              :disabled="!ids.length > 0"
              >删除</el-button
            >
            <el-button
              size="small"
              icon="el-icon-download"
              type="primary"
              @click="doExport"
              >导出</el-button
            >
            <el-button
              size="small"
              icon="el-icon-refresh"
              type="primary"
              :disabled="!ids.length > 0"
              >重置密码</el-button
            >
          </el-row>
        </div>
        <!--表单渲染-->
        <el-dialog
          append-to-body
          :close-on-click-modal="false"
          :before-close="close"
          :visible.sync="isAdd"
          :title="title"
          width="720px"
        >
          <el-form
            ref="form"
            :inline="true"
            :model="form"
            :rules="rules"
            v-if="isAdd"
            size="small"
            label-width="86px"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户类型" prop="userType">
                  <el-select v-model="form.userType" style="width: 192px">
                    <el-option
                      v-for="item in userTypeList"
                      :key="item.label"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户名" prop="nickName">
                  <el-input v-model="form.nickName" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="密码" prop="password">
                  <el-input
                    v-model.number="form.password"
                    show-password
                    style="width: 192px"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model.number="form.phone" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="cardNum">
                  <el-input v-model="form.cardNum" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="所属单位" prop="deptName">
                  <!-- :load-options="loadDepts" -->
                  <treeselect
                    v-model="form.deptName"
                    :options="deptList"
                    style="width: 480px"
                    placeholder="选择所属单位"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="描述" prop="desc">
                  <el-input
                    type="textarea"
                    :rows="2"
                    style="width: 480px"
                    v-model.number="form.desc"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="close">取消</el-button>
            <el-button type="primary" @click="submit(subType)">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table
          ref="table"
          v-loading="loading"
          :data="tableList"
          style="width: 100%"
          height="500px"
          @selection-change="selectionChangeHandler"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="userType" label="用户类型">
            <template slot-scope="scope">
              <span>{{
                userTypeList.filter(
                  (item) => item.value == scope.row.userType
                )[0].label
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="nickName" label="用户名" />
          <el-table-column prop="password" label="密码" />
          <el-table-column prop="phone" width="100" label="手机号" />
          <el-table-column prop="cardNum" width="150" label="身份证号" />
          <el-table-column prop="deptName	" label="所属单位">
            <template slot-scope="scope">
              <span>{{ mapValueToLabel(scope.row.deptName) }}</span>
            </template>
          </el-table-column>
          <el-table-column width="135" prop="desc" label="描述" />
          <el-table-column
            label="操作"
            width="155"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button size="mini" @click="add(scope.row, scope.$index)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="deleteUser(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <el-pagination
          background
          :hide-on-single-page="true"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="400"
        >
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { doExport } from "@/utils/util.js";
import Treeselect from "@riophae/vue-treeselect";
export default {
  name: "user",
  components: { Treeselect },
  data() {
    return {
      // 选中列表
      ids: [],
      tableIndex: null,
      // 提交类型
      subType: "add",
      currentPage: 1,
      // 表格加载
      loading: false,
      // 弹框标题
      title: "",
      // 用户类型列表
      userTypeList: [
        { label: "审核员", value: 0 },
        { label: "管理员", value: 1 },
      ],
      user: {
        id: null,
      },
      form: {},
      // rules 表单验证
      rules: {
        userType: [
          { required: true, message: "请选择系统编码", trigger: "change" },
        ],
        nickName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        deptName: [
          { required: true, message: "请选择所属单位", trigger: "change" },
        ],
      },
      dept: [],
      // 添加用户
      isAdd: false,
      // 列表数据
      tableList: [
        {
          id: 1,
          userType: 0,
          nickName: "用户名1",
          phone: "137*****025",
          deptName: 201104,
          desc: "这是一段描述",
          password: "**********",
          cardNum: "1304311*********21",
        },
      ],
      // 搜索项数据
      queryData: {
        enabled: [],
        deptName: "",
        createTime: null,
        blurry: null,
        deptId: null,
      },
      enabledTypeOptions: [
        { name: "激活", key: "1" },
        { name: "锁定", key: "2" },
      ],
      // 部门树
      deptDatas: [
        {
          deptName: "沧州市人民政府",
          children: [
            { deptName: "沧州市大数据中心" },
            { deptName: "沧州市外事服务中心" },
            { deptName: "沧州市政府办公室综合事务保障中心" },
            { deptName: "沧州市机关事务保障中心" },
          ],
        },
      ],
      defaultProps: { children: "children", label: "deptName" },
      deptList: [
        {
          children: [
            { id: 201101, label: "沧州市大数据中心" },
            { id: 201102, label: "沧州市外事服务中心" },
            { id: 201103, label: "沧州市政府办公室综合事务保障中心" },
            { id: 201104, label: "沧州市机关事务保障中心" },
          ],
          id: 2011,
          label: "沧州市人民政府",
        },
      ],
      // 时间快捷按钮
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    deleteUser() {},
    mapValueToLabel(value) {
      // 遍历deptList数组
      for (const unit of this.deptList) {
        // 先判断当前单位是否为目标单位
        if (unit.id === value) {
          return unit.label;
        }

        // 在children属性中递归查找目标单位
        const targetUnit = unit.children.find((child) => child.id === value);

        if (targetUnit) {
          return targetUnit.label;
        }
      }

      // 没有找到对应id的单位
      return null;
    },
    // 切换部门
    handleNodeClick(data) {
      if (data.pid === 0) {
        this.queryData.deptId = null;
      } else {
        this.queryData.deptId = data.id;
      }
      this.toQuery();
    },
    submit(type) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.isAdd = false;
          if (type == "add") {
            this.tableList.push(this.form);
          } else {
            this.$set(this.tableList, this.tableIndex, this.form);
          }
          this.close();
        }
      });
    },
    toQuery() {},
    add(row, index) {
      this.tableIndex = index;
      this.isAdd = true;
      if (row != undefined && row != "undefined") {
        this.title = "编辑";
        this.subType = "edit";
        this.form = { ...row };
      } else {
        this.title = "新增用户";
        this.subType = "add";
        this.reset();
      }
    },
    reset() {
      this.tableIndex = null;
      this.form = {
        userType: null,
        nickName: null,
        phone: null,
        deptName: null,
        desc: null,
        password: null,
        cardNum: null,
      };
    },
    close() {
      this.isAdd = false;
      this.title = "";
      this.reset();
    },
    // 获取左侧部门数据
    getDeptDatas(node, resolve) {
      const sort = "id,desc";
      const params = { sort: sort };
      if (typeof node !== "object") {
        if (node) {
          params["name"] = node;
        }
      } else if (node.level !== 0) {
        params["pid"] = node.data.id;
      }
      setTimeout(() => {
        // getDepts(params).then((res) => {
        //   if (resolve) {
        //     resolve(res.content);
        //   } else {
        //     this.deptDatas = res.content;
        //   }
        // });
      }, 100);
    },
    getDepts() {
      // getDepts({ enabled: true }).then((res) => {
      //   this.depts = res.content.map(function (obj) {
      //     if (obj.hasChildren) {
      //       obj.children = null;
      //     }
      //     if (!obj.hasChildren) {
      //       delete obj.children;
      //     }
      //     return obj;
      //   });
      // });
    },
    // 导出
    doExport() {
      doExport();
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        // getDepts({ enabled: true, pid: parentNode.id }).then((res) => {
        //   parentNode.children = res.content.map(function (obj) {
        //     if (obj.hasChildren) {
        //       obj.children = null;
        //     }
        //     if (!obj.hasChildren) {
        //       delete obj.children;
        //     }
        //     return obj;
        //   });
        //   setTimeout(() => {
        //     callback();
        //   }, 200);
        // });
      }
    },
    // 多选框选中数据
    selectionChangeHandler(selection) {
      this.ids = selection.map((item) => item.id);
      console.log(this.ids);
    },
  },
};
</script>

<style scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>

 